#!/bin/bash
set -e

fileName="{{fileName}}"
contentType="{{contentType}}"
targetDir="{{targetDir}}"
fileOwner="{{fileOwner}}"
fileGroup="{{fileGroup}}"
fileMode="{{fileMode}}"
overWrite="{{overWrite}}"

mkdir -p $targetDir

path=$targetDir/$fileName
# skip if overWrite is false and file already exists.
if [ "$overWrite" = "False" ] && [ -f $path ]; then
  echo "file already exists and overWrite is set false, skip."
  exit 0
fi

tmpFile=$(mktemp)
cat > "$tmpFile" <<'EOF'
{{fileContent}}
EOF

if [ "$contentType" = "Base64" ]; then
  base64 -di "$tmpFile" > $path
  rm -f "$tmpFile"
else
  mv -f "$tmpFile" "$path"
fi

chgrp $fileGroup "$path"
chown $fileOwner "$path"
chmod $fileMode "$path"

echo "upload file success."
